/*
 * Copyright (C) 2012 fabien
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights 
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.flickr.api.auth;

import com.sun.jersey.api.uri.UriBuilderImpl;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.ws.rs.core.UriBuilder;
import oauth.signpost.OAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author fabien
 */
class AuthenticationServer extends Thread {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationServer.class);
    //
    private final URI uri;
    private final Object mutex = new Object();
    private String authCode;

    public AuthenticationServer() {
        super();
        setName("OAuth-server-listener");

        UriBuilder uriBuilder = new UriBuilderImpl();
        uriBuilder.host("localhost");
        uriBuilder.port(generatePort());
        uriBuilder.path("oauth");
        uri = uriBuilder.build();
    }

    public URI getUri() {
        return uri;
    }

    @Override
    public synchronized void start() {
        super.start();
        try {
            synchronized (mutex) {
                mutex.wait();
            }
        } catch (InterruptedException ex) {
        }
    }

    @Override
    public void run() {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", uri.getPort()), uri.getPort());
            LOGGER.debug("Authentication server started on port {}", uri.getPort());
            server.createContext("/oauth", new AuthHandler(server));
            server.start();

        } catch (Exception ex) {
            throw new UnsupportedOperationException(ex.getMessage(), ex);
        }
    }

    public String getAuthenticationCode() {
        return authCode;
    }

    private int generatePort() {
        Random rand = new Random();
        int value;
        while (true) {
            value = rand.nextInt() % 65535;
            if (value > 1024) {
                return value;
            }
        }
    }

    private class AuthHandler implements HttpHandler {
        private final HttpServer server;

        public AuthHandler(HttpServer server) {
            this.server = server;
        }
        
        @Override
        public void handle(HttpExchange handler) throws IOException {
            LOGGER.debug("Client connected");
            Map<String, String> queryParams = getQueryMap(handler.getRequestURI().getQuery());
            String code = queryParams.get(OAuth.OAUTH_VERIFIER);
            if(code != null) {
                authCode = code;
                LOGGER.debug("Authentication code retrieved");
                handler.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
                
            } else {
                authCode = null;
                handler.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
            }
            
            // Stop the server
            handler.close();
            server.stop(3);
            synchronized (mutex) {
                mutex.notify();
            }
        }

        public Map<String, String> getQueryMap(String query) {
            String[] params = query.split("&");
            Map<String, String> map = new HashMap<String, String>();
            for (String param : params) {
                String name = param.split("=")[0];
                String value = param.split("=")[1];
                map.put(name, value);
            }
            return map;
        }
    }
}
